# plugs/alias.py
#
#

""" implement aliases commands """

__copyright__ = 'this file is in the public domain'

from gozerbot.aliases import aliases
from gozerbot.commands import cmnds
from gozerbot.examples import examples
from gozerbot.plughelp import plughelp
from gozerbot.generic import lockdec
import thread

plughelp.add('alias', 'support for aliases')

aliaslock = thread.allocate_lock()
locked = lockdec(aliaslock)

def handle_aliassearch(bot, ievent):
    """ alias-search <what> .. search aliases """
    try:
        what = ievent.args[0]
    except IndexError:
        ievent.missing('<what>')
        return
    result = []
    res = ""
    for i, j in aliases.data.iteritems():
        if what in i or what in j:
            result.append((i, j))
    if not result:
        ievent.reply('no %s found' % what)
    else:
        for i in result:
            res += "%s: %s .. " % i
        ievent.reply(res[:-4])

cmnds.add('alias-search', handle_aliassearch, 'USER')
examples.add('alias-search', 'search aliases',' alias-search')

@locked
def handle_aliasset(bot, ievent):
    """ alais-set <from> <to> .. set alias """
    try:
        (aliasfrom, aliasto) = (ievent.args[0], ' '.join(ievent.args[1:]))
    except IndexError:
        ievent.missing('<from> <to>')
        return
    if not aliasto:
        ievent.missing('<from> <to>')
        return
    # add alias and save
    aliases.data[aliasfrom] = aliasto
    aliases.save()
    ievent.reply('alias added')

cmnds.add('alias-set', handle_aliasset, 'OPER')
examples.add('alias-set', 'alias-set <from> <to> .. define alias', \
'alias-set ll list')
aliases.data['alias'] = 'alias-set'

@locked
def handle_delalias(bot, ievent):
    """ alias-del <word> .. delete alias """
    try:
        what = ievent.args[0]
    except IndexError:
        ievent.missing('<what>')
        return
    # del alias and save
    try:
        del aliases.data[what]
    except KeyError:
        ievent.reply('there is no %s alias' % what)
        return
    aliases.save()
    ievent.reply('alias deleted')

cmnds.add('alias-del', handle_delalias, 'OPER')
examples.add('alias-del', 'alias-del <what> .. delete alias', 'alias-del ll')

def handle_getalias(bot, ievent):
    """ alias-get <word> .. show alias """
    try:
        what = ievent.args[0]
    except IndexError:
        ievent.missing('<what>')
        return
    # del alias and save
    try:
        alias = aliases.data[what]
    except KeyError:
        ievent.reply('there is no %s alias' % what)
        return
    if alias:
        ievent.reply(alias)
    else:
        ievent.reply('no %s alias found' % what)

cmnds.add('alias-get', handle_getalias, 'USER')
examples.add('alias-get', 'alias-get <what> .. get alias', 'alias-get ll')
